package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Map;
import java.util.Random;

//用户
@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    SmsTemplate smsTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserMapper userMapper;

    @Override
    public void sendMsg(String phone) {
        //String code = RandomUtil.randomNumbers(6);
        String code="123";//todo 产品上线之前，需要实现真实短信发生
        //2.发送短信
        //smsTemplate.sendSms(phone,code);
        log.info("发送短信成功:{}",code);
        //redis储存一份验证码，有效期5分钟
        redisTemplate.opsForValue().set(Constant.USER_PHONE_CODE+phone,code,Duration.ofSeconds(300));

    }

    @Override
    public String login(String phone, String code) {
        //校验验证码
        String rcode =(String) redisTemplate.opsForValue().get(Constant.USER_PHONE_CODE + phone);
        //取出redis中验证码
       // String codeRedis = (String) redisTemplate.opsForValue().get(Constant.USER_PHONE_CODE+phone);
        if(!StrUtil.equals(code,rcode)){
            throw new CustomException("验证码不正确");
        }

        //查询数据库中是否有此号码
        //select * from user where phone = ?;
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,phone);
        User user = userMapper.selectOne(qw);
        //如果没有存入
        if(user == null){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        }
        //制作token
        Map<String, Object> map = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(map);
        redisTemplate.delete(Constant.USER_PHONE_CODE+phone);


        return token;
    }
}
